import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
import { h } from 'vue'

// const MemberHome = () => import('@/views/member/home')
// const MemberOrder = () => import('@/views/member/order')
// const MemberOrderDetail = () => import('@/views/member/order/detail')

const routes = [
  {
    path: '/',
    component: () => import('@/views/Layout/Layout.vue'),
    children: [
      {
        path: '/',
        component: () => import('@/views/Home')
      },
      {
        path: '/category/:id',
        component: () => import('@/views/Category')
      },
      {
        path: '/category/sub/:id',
        component: () => import('@/views/Category/sub.vue')
      },
      {
        path: '/product/:id',
        component: () => import('@/views/Goods')
      },
      {
        path: '/cart',
        component: () => import('@/views/Cart')
      },
      {
        path: '/member/checkout',
        component: () => import('@/views/member/pay/checkout')
      },
      {
        path: '/member/pay',
        component: () => import('@/views/member/pay/index')
      },
      {
        path: '/pay/callback',
        component: () => import('@/views/member/pay/result')
      },
      // 个人中心
      {
        path: '/member',
        component: () => import('@/views/member/Layout'),
        children: [
          { path: '/member', component: () => import('@/views/member/home') },
          // { path: '/member/order', component: MemberOrder },
          // { path: '/member/order/:id', component: MemberOrderDetail }
          {
            path: '/member/order',
            // 创建一个RouterView容器形成嵌套关系
            component: { render: () => h(<RouterView />) },
            children: [
              { path: '', component: () => import('@/views/member/order') },
              { path: ':id', component: () => import('@/views/member/order/detail') }
            ]
          }

        ]
      }

    ]
  },
  { path: '/login', component: () => import('@/views/Login') },
  { path: '/login/callback', component: () => import('@/views/Login/callback') }
]

// 创建路由实例
const router = createRouter({
  // 使用hash方式实现路由
  history: createWebHashHistory(),
  routes,
  // 每次切换路由的时候滚动到页面顶部
  scrollBehavior () {
    // vue2.0  x  y  控制 vue3.0  left  top 控制
    return { left: 0, top: 0 }
  }
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 需要登录的路由：地址是以 /member 开头
  const { profile } = store.state.user
  // 跳转地址以 /member 开头
  if (!profile.token && to.path.startsWith('/member')) {
    // 携带当前地址
    return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
  }
  next()
})

export default router
